package com.sharker.myproject.commom.config.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.sharker.myproject.domain.Permission;
import com.sharker.myproject.domain.Role;
import com.sharker.myproject.domain.User;
import com.sharker.myproject.service.PermissionService;
import com.sharker.myproject.service.Userservice;

@Configuration
public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private Userservice userService;
	@Autowired
	private PermissionService permissionService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User user = (User) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 根据用户名查询当前用户拥有的角色
		List<Role> roles = userService.findRoles(user.getName());
		Set<String> roleNames = new HashSet<String>();
		for (Role role : roles) {
			roleNames.add(role.getName());
		}
		// 将角色名称提供给info
		authorizationInfo.setRoles(roleNames);
		// 根据用户名查询当前用户权限
		List<Permission> permissions = permissionService.findPermissions(user.getName());
		Set<String> permissionNames = new HashSet<String>();
		for (Permission permission : permissions) {
			permissionNames.add(permission.getName());
		}
		// 将权限名称提供给info
		authorizationInfo.setStringPermissions(permissionNames);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken passwordToken=(UsernamePasswordToken)token;
		User user = userService.getUserByLoginName(passwordToken.getUsername());
		if(null!=user&&user.getPassword().equals(new String(passwordToken.getPassword()))){
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
		throw new UnauthenticatedException();
	}

}
